package com.shopping.service;

import java.util.List;

import com.shopping.dao.CategoryDAO;
import com.shopping.modean.Category;

public class CategoryService {

	private static final int ROOT_CATEGORY_GRADE = 1;
	private static final int ROOT_CATEGORY_PID = 0;
	
	private CategoryDAO categoryDAO = new CategoryDAO();
	
	/**
	 * 保存根分类
	 * 
	 * @data 2018-06-05
	 */
	public void addRootCategory(String name,String descr) {
		Category c = new Category();
		c.setName(name);
		c.setDescr(descr);
		c.setPid(ROOT_CATEGORY_PID);
		c.setLeaf(true);//leaf：是否为叶子，1是0否
		c.setGrade(ROOT_CATEGORY_GRADE);
		categoryDAO.insert(c);
	}
	
	/**
	 * 保存子分类
	 * 
	 * @data 2018-06-09
	 */
	public void addChildCategory(int pid,String name,String descr) {
		
		Category parent = categoryDAO.getCategoryById(pid);
		if(parent == null) {
			System.err.println("parent不存在，请检查pid:" + pid);
		} else {
			Category c = new Category();
			c.setName(name);
			c.setDescr(descr);
			c.setPid(pid);
			c.setLeaf(true);
			c.setGrade(parent.getGrade() + 1);
			categoryDAO.insert(c);
			
			if(parent.isLeaf()) {
				//因为parent有了叶子，就不再是叶子了
				categoryDAO.updateCategoryLeafById(pid,false);
			}
		}
	}
	
	/**
	 * 分类列表
	 * 
	 * @date 2018-06-09
	 */
	public List<Category> list() {
		List<Category> categorys = categoryDAO.getCategorys();
		System.out.println("查询分类列表,categoryrSize:" + categorys.size());
		return categorys;
	}
	
	/**
	 * 分类列表
	 * 
	 * @date 2018-06-09
	 */
	public List<Category> list(int pid) {
		List<Category> categorys = categoryDAO.getCategorys(pid);
		for(Category c : categorys) {
			List<Category> subs = categoryDAO.getCategorys(c.getId());
			c.setLeafSize(subs.size());
		}
		System.out.println("查询分类列表,categoryrSize:" + categorys.size());
		return categorys;
	}
	
	/**
	 * 分类详情
	 * 
	 * @date 2018-06-20
	 */
	public Category detail(int id) {
		return categoryDAO.getCategoryById(id);
	}
	
	/**
	 * 分类修改
	 * 
	 * @date 2018-06-20
	 */
	public void update(Category c) {
		categoryDAO.updateById(c);
	}
	
	/**
	 * 删除分类
	 * 
	 * @date 2018-06-20
	 */
	public void delete(int id) {
		categoryDAO.deleteById(id);
	}
	
}
